package com.analog.mserver.service.user;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.analog.mserver.domain.user.RoleEntity;
import com.analog.mserver.domain.user.UserEntity;
import com.analog.mserver.jwt.JwtUtil;
import com.analog.mserver.repository.user.RoleRepository;
import com.analog.mserver.repository.user.UserRepository;
import com.analog.mserver.repository.user.UserRoleRepository;
import com.analog.mserver.service.base.BaseService;
import com.analog.mserver.utils.StringUtils;
import com.analog.mserver.vo.user.RoleVO;
import com.analog.mserver.vo.user.UserVO;

@Service("userService")
public class UserService extends BaseService{

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserRoleRepository userRoleRepository;
	@Autowired
	private RoleRepository roleRepository;
	
	public UserEntity findByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public Boolean login(String username, String password) {
		UserEntity user = userRepository.findByUsername(username);
		
		if(user == null ) {
			return false;
		
		}
		if(!user.getPassword().equalsIgnoreCase(password)) {
			return false;
		}
		
		return true;
	}

	/**
	 * 验证token 是否有效
	 * @param token
	 * @return
	 */
	public boolean verificationToken(String token) {
		String username = JwtUtil.getUsername(token);
		if(StringUtils.isBlank(username)) {
			return false;
		}
		
		UserEntity user = userRepository.findByUsername(username);
		
		if(user == null) {
			return false;
		}
		
		return JwtUtil.verify(token, username, user.getPassword());
	}

	public Page<UserEntity> findUserPageList(UserVO vo) {
		PageRequest buildPageRequest = buildPageRequest(vo.getPage(), vo.getLimit());
		return userRepository.findAll(buildPageRequest);
	}

	public Page<RoleEntity> findRoleList(RoleVO vo) {
		PageRequest buildPageRequest = buildPageRequest(vo.getPage(), vo.getLimit());
		return roleRepository.findAll(buildPageRequest);
	}
	
	public RoleEntity saveRole(RoleVO vo) {
		RoleEntity po = new RoleEntity();
		BeanUtils.copyProperties(vo, po);
		return roleRepository.save(po);
	}

	
}
